package com.example.demo.service;

import com.example.demo.model.request.ExternalApiRequest;
import com.example.demo.model.request.FrontendRequest;
import com.example.demo.model.response.PredictionResponse;
import com.example.demo.model.response.SimilarStudentsResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TempService {
    // 外部API地址（复用原配置）
    private static final String PREDICT_API_URL = "http://192.168.209.178:8000/predict";
    private static final String SIMILAR_STUDENTS_API_URL = "http://192.168.209.178:8000/similar_students";

    // 依赖注入（替代原硬编码创建）
    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;
    private static final Logger logger = LoggerFactory.getLogger(TempService.class); // 修正Logger所属类

    // 构造注入（由Spring容器管理）
    public TempService(RestTemplate restTemplate, ObjectMapper objectMapper) {
        this.restTemplate = restTemplate;
        this.objectMapper = objectMapper;
    }

    /**
     * 获取相似学生（整合PredictionService的转换和默认响应逻辑）
     */
    public SimilarStudentsResponse getSimilarStudents(FrontendRequest frontendRequest) {
        logger.info("开始调用相似学生API，学生ID: {}", frontendRequest.getStudent_id());

        // 1. 转换前端请求为外部API格式
        ExternalApiRequest apiRequest = convertToExternalApiRequest(frontendRequest);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept", "application/json;charset=UTF-8");
        HttpEntity<ExternalApiRequest> requestEntity = new HttpEntity<>(apiRequest, headers);

        try {
            // 记录请求数据用于调试
            String requestJson = objectMapper.writeValueAsString(apiRequest);
            logger.info("相似学生API请求数据: {}", requestJson);

            // 2. 发送请求到外部API
            ResponseEntity<String> rawResponse = restTemplate.exchange(
                    SIMILAR_STUDENTS_API_URL,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );

            logger.info("相似学生API返回状态码: {}", rawResponse.getStatusCode());
            logger.info("相似学生API返回原始响应: {}", rawResponse.getBody());

            if (rawResponse.getBody() == null || rawResponse.getBody().trim().isEmpty()) {
                logger.warn("相似学生API返回空响应，使用默认数据");
                return createDefaultSimilarStudentsResponse(frontendRequest.getStudent_id());
            }

            // 解析响应
            SimilarStudentsResponse response = objectMapper.readValue(rawResponse.getBody(), SimilarStudentsResponse.class);
            logger.info("成功解析相似学生响应: {}", response);
            return response;

        } catch (HttpStatusCodeException e) {
            String errorBody = e.getResponseBodyAsString();
            logger.error("相似学生API返回HTTP错误: {} - 响应体: {}", e.getStatusCode(), errorBody);
            return createDefaultSimilarStudentsResponse(frontendRequest.getStudent_id());
        } catch (Exception e) {
            logger.error("调用相似学生API失败: {}", e.getMessage(), e);
            return createDefaultSimilarStudentsResponse(frontendRequest.getStudent_id());
        }
    }

    /**
     * 预测（整合PredictionService的转换和默认响应逻辑）
     */
    public PredictionResponse predict(FrontendRequest frontendRequest) {
        // 1. 转换前端请求为外部API格式
        ExternalApiRequest apiRequest = convertToExternalApiRequest(frontendRequest);

        // 记录请求数据
        try {
            String requestJson = objectMapper.writeValueAsString(apiRequest);
            logger.info("发送到预测API的请求数据: {}", requestJson);
        } catch (Exception e) {
            logger.warn("无法序列化预测请求数据: {}", e.getMessage());
        }

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept", "application/json;charset=UTF-8");
        HttpEntity<ExternalApiRequest> requestEntity = new HttpEntity<>(apiRequest, headers);

        try {
            // 2. 调用外部API
            ResponseEntity<String> rawResponse = restTemplate.exchange(
                    PREDICT_API_URL,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );

            logger.info("预测API返回状态码: {}", rawResponse.getStatusCode());
            logger.info("预测API返回原始响应: {}", rawResponse.getBody());

            if (rawResponse.getBody() == null || rawResponse.getBody().trim().isEmpty()) {
                logger.warn("预测API返回空响应，使用默认数据");
                return createDefaultPredictionResponse(frontendRequest.getStudent_id());
            }

            // 解析响应
            PredictionResponse response = objectMapper.readValue(rawResponse.getBody(), PredictionResponse.class);
            logger.info("成功解析预测响应: {}", response);
            return response;

        } catch (HttpStatusCodeException e) {
            String errorBody = e.getResponseBodyAsString();
            logger.error("预测API返回HTTP错误: {} - 响应体: {}", e.getStatusCode(), errorBody);
            return createDefaultPredictionResponse(frontendRequest.getStudent_id());
        } catch (Exception e) {
            logger.error("调用预测API失败: {}", e.getMessage(), e);
            return createDefaultPredictionResponse(frontendRequest.getStudent_id());
        }
    }

    /**
     * 转换前端请求为外部API所需格式（迁移自PredictionService）
     */
    private ExternalApiRequest convertToExternalApiRequest(FrontendRequest frontendRequest) {
        ExternalApiRequest apiRequest = new ExternalApiRequest();
        apiRequest.setStudent_id(frontendRequest.getStudent_id());
        apiRequest.setName(frontendRequest.getName());
        apiRequest.setGpa(frontendRequest.getGpa());
        apiRequest.setCet4(frontendRequest.getCet4());
        apiRequest.setMath1(frontendRequest.getMath1());
        apiRequest.setMath2(frontendRequest.getMath2());
        apiRequest.setEnglish1(frontendRequest.getEnglish1());
        apiRequest.setEnglish2(frontendRequest.getEnglish2());
        apiRequest.setEnglish3(frontendRequest.getEnglish3());
        apiRequest.setEnglish4(frontendRequest.getEnglish4());
        apiRequest.setMajor(frontendRequest.getMajor());
        apiRequest.setCollege(frontendRequest.getCollege());
        apiRequest.setTargetSchool(frontendRequest.getTargetSchool());
        return apiRequest;
    }

    /**
     * 创建默认相似学生响应（迁移自PredictionService）
     */
    private SimilarStudentsResponse createDefaultSimilarStudentsResponse(String studentId) {
        SimilarStudentsResponse response = new SimilarStudentsResponse();
        response.setStudentId(studentId);

        List<Map<String, Object>> similarStudents = new ArrayList<>();
        // 默认学生1
        Map<String, Object> student1 = new HashMap<>();
        student1.put("studentId", "S001");
        student1.put("name", "张三");
        student1.put("gpa", 3.8);
        student1.put("cet4", 550);
        student1.put("similarity", 0.92);
        similarStudents.add(student1);

        // 默认学生2
        Map<String, Object> student2 = new HashMap<>();
        student2.put("studentId", "S002");
        student2.put("name", "李四");
        student2.put("gpa", 3.6);
        student2.put("cet4", 520);
        student2.put("similarity", 0.85);
        similarStudents.add(student2);

        // 默认学生3
        Map<String, Object> student3 = new HashMap<>();
        student3.put("studentId", "S003");
        student3.put("name", "王五");
        student3.put("gpa", 3.9);
        student3.put("cet4", 580);
        student3.put("similarity", 0.88);
        similarStudents.add(student3);

        response.setData(similarStudents);
        logger.info("创建默认相似学生响应: {}", response);
        return response;
    }

    /**
     * 创建默认预测响应（迁移自PredictionService）
     */
    private PredictionResponse createDefaultPredictionResponse(String studentId) {
        PredictionResponse response = new PredictionResponse();
        response.setStudentId(studentId);
        response.setPrediction(1.0);
        response.setProbability(99.28);
        response.setDescription("可能考上985/211高校（概率：99.28%）");
        logger.info("创建默认预测响应: {}", response);
        return response;
    }

    /**
     * 测试外部API连接（迁移自PredictionService）
     */
    public boolean testExternalApiConnection() {
        try {
            logger.info("测试外部API连接: {}", PREDICT_API_URL);
            String testUrl = PREDICT_API_URL.substring(0, PREDICT_API_URL.lastIndexOf("/"));
            restTemplate.getForObject(testUrl, String.class);
            logger.info("外部API连接测试成功");
            return true;
        } catch (Exception e) {
            logger.error("外部API连接测试失败: {}", e.getMessage());
            return false;
        }
    }
}